package com.zscat.mallplus.sys.service.impl;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zscat.mallplus.center.entity.CenterColumnsRecommend;
import com.zscat.mallplus.center.mapper.CenterColumnsRecommendMapper;
import com.zscat.mallplus.component.OssAliyunUtil;
import com.zscat.mallplus.enums.StatusEnum;
import com.zscat.mallplus.fenxiao.mapper.FenxiaoConfigMapper;
import com.zscat.mallplus.pms.mapper.PmsBrandMapper;
import com.zscat.mallplus.pms.mapper.PmsProductAttributeCategoryMapper;
import com.zscat.mallplus.pms.mapper.PmsProductCategoryMapper;
import com.zscat.mallplus.pms.service.IPmsProductService;
import com.zscat.mallplus.sys.entity.AdminDayStatics;
import com.zscat.mallplus.sys.entity.SysQiniuConfig;
import com.zscat.mallplus.sys.entity.SysStore;
import com.zscat.mallplus.sys.entity.SysSystemSetting;
import com.zscat.mallplus.sys.entity.SysUser;
import com.zscat.mallplus.sys.entity.SysUserRole;
import com.zscat.mallplus.sys.mapper.AdminDayStaticsMapper;
import com.zscat.mallplus.sys.mapper.SysQiniuConfigMapper;
import com.zscat.mallplus.sys.mapper.SysRoleMapper;
import com.zscat.mallplus.sys.mapper.SysStoreMapper;
import com.zscat.mallplus.sys.mapper.SysSystemSettingMapper;
import com.zscat.mallplus.sys.mapper.SysUserMapper;
import com.zscat.mallplus.sys.mapper.SysUserRoleMapper;
import com.zscat.mallplus.sys.service.ISysStoreRankService;
import com.zscat.mallplus.sys.service.ISysStoreService;
import com.zscat.mallplus.util.MatrixToImageWriter;
import com.zscat.mallplus.util.UserUtils;
import com.zscat.mallplus.utils.CreateNamePicture;
import com.zscat.mallplus.utils.ValidatorUtils;

import lombok.extern.slf4j.Slf4j;


/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zscat
 * @since 2019-05-18
 */
@Slf4j
@Service
public class SysStoreServiceImpl extends ServiceImpl<SysStoreMapper, SysStore> implements ISysStoreService {

    @Autowired
    OssAliyunUtil aliyunOSSUtil;
    @Resource
    SysUserRoleMapper userRoleMapper;
    @Resource
    FenxiaoConfigMapper fenxiaoConfigMapper;
    @Resource
    private SysStoreMapper storeMapper;
    @Resource
    private SysUserMapper userMapper;
    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private IPmsProductService productService;

    @Resource
    private PmsProductCategoryMapper pmsProductCategoryMapper;
    @Resource
    private PmsProductAttributeCategoryMapper pmsProductAttributeCategoryMapper;
    @Resource
    private PmsBrandMapper pmsBrandMapper;
    @Resource
    private SysSystemSettingMapper sysSystemSettingMapper;
    @Resource
    private SysQiniuConfigMapper qiniuConfigMapper;
    @Resource
    private CenterColumnsRecommendMapper centerColumnsRecommendMapper;
    @Resource
    private AdminDayStaticsMapper adminDayStaticsMapper;
    @Resource
    private SysRoleMapper roleMapper;
    @Resource
    private ISysStoreRankService storeRankService;
    
    @Transactional
    @Override
    public boolean saveStore(SysStore entity) {
        if (ValidatorUtils.empty(entity.getName())) {
            return false;
        }
        SysStore sysStore = storeMapper.selectOne(new QueryWrapper<SysStore>().eq("name",entity.getName()));
        if (sysStore != null) {
            return false;
        }
        SysSystemSetting mallplusProperties = sysSystemSettingMapper.selectById(1);

        entity.setStatus(3);
        entity.setTryTime(new Date());
        entity.setCreateTime(new Date());
        storeMapper.insert(entity);
        String url = mallplusProperties.getSiteUrl()+"/#/pages/store/businessDetails?id=" + entity.getId();
        //要添加到二维码下面的文字
        String words = entity.getName() + "的二维码";
        //调用刚才的工具类
        ByteArrayResource qrCode = MatrixToImageWriter.createQrCode(url, words);
        InputStream inputStream = new ByteArrayInputStream(qrCode.getByteArray());
        SysQiniuConfig config =qiniuConfigMapper.selectById(1);
        entity.setContactQrcode(aliyunOSSUtil.upload("png", inputStream,config));
        
        entity.setContactQq(storeRankService.getById(entity.getHit()).getName());
        
        storeMapper.updateById(entity);
        //初始化AdminDayStatics
        AdminDayStatics adminDayStatics = new AdminDayStatics();
        adminDayStatics.setStoreId(entity.getId());
        adminDayStatics.setStoreName(entity.getName());
        adminDayStatics.setCreateTime(new Date());
        adminDayStaticsMapper.insert(adminDayStatics);
        SysUser user = new SysUser();
        user.setUsername(entity.getName());
        user.setNickName(entity.getName());
        SysUser umsAdminList = userMapper.selectByUserName(entity.getName());
        if (umsAdminList != null) {
            return false;
        }
        user.setStatus(1);
        user.setSupplyId(0L);
        user.setPassword(passwordEncoder.encode("123456"));
        user.setCreateBy(UserUtils.getCurrentMember().getNickName());
        user.setCreateTime(new Date());
        user.setIcon(entity.getLogo());
        if (ValidatorUtils.empty(user.getIcon())){
            try {
                File tempFile = CreateNamePicture.generateImg(user.getNickName(),System.getProperty("java.io.tmpdir"),System.currentTimeMillis()+user.getUsername());
                user.setIcon(aliyunOSSUtil.upload("png",new FileInputStream(tempFile),config));
            } catch (IOException e) {
                log.error("用户名图片生成失败");
            }
        }
        user.setNickName(entity.getName());
        user.setStoreId(entity.getId());
        user.setStoreName(entity.getName());
        user.setRoleId(2);
        user.setNote(roleMapper.getRoleName(user.getRoleId()));
        userMapper.insert(user);
        SysUserRole userRole = new SysUserRole();
        userRole.setRoleId(2L);
        userRole.setAdminId(user.getId());
        userRoleMapper.insert(userRole);

        for (int i = 0; i < 5; i++) {
            CenterColumnsRecommend centerColumnsRecommend = new CenterColumnsRecommend();
            switch (i) {
      case 0:
       centerColumnsRecommend.setRecommendName("今日科普");
             centerColumnsRecommend.setRecommendType("资讯");
             centerColumnsRecommend.setRecommendLimit(1);
       break;
      case 1:
       centerColumnsRecommend.setRecommendName("秒杀&拼团");
             centerColumnsRecommend.setRecommendType("商品");
             centerColumnsRecommend.setRecommendLimit(2);
       break;
      case 2:
       centerColumnsRecommend.setRecommendName("精品课程");
             centerColumnsRecommend.setRecommendType("商品");
             centerColumnsRecommend.setRecommendLimit(3);
       break;
      case 3:
       centerColumnsRecommend.setRecommendName("玩酷好物");
             centerColumnsRecommend.setRecommendType("商品");
             centerColumnsRecommend.setRecommendLimit(4);
       break;
      case 4:
       centerColumnsRecommend.setRecommendName("猜你喜欢");
             centerColumnsRecommend.setRecommendType("资讯");
             centerColumnsRecommend.setRecommendLimit(3);
       break; 
      default:
       break;
      }
            centerColumnsRecommend.setStoreId(entity.getId().longValue());
            centerColumnsRecommendMapper.insertCenterColumnsRecommend(centerColumnsRecommend);
     }
       /* if (entity.getType() != null) {
            CompletableFuture.runAsync(() -> {

                BakCategory category = bakCategoryMapper.selectById(entity.getType());
                PmsProductCategory pmsProductCategory = new PmsProductCategory();
                pmsProductCategory.setIcon(category.getIconUrl());
                pmsProductCategory.setName(category.getName());
                pmsProductCategory.setKeywords(category.getKeywords());
                pmsProductCategory.setParentId(category.getPid().longValue());
                pmsProductCategory.setLevel(Integer.parseInt(category.getLevel().substring(1)));
                pmsProductCategoryMapper.insert(pmsProductCategory);


                PmsProductAttributeCategory pmsProductAttributeCategory = new PmsProductAttributeCategory();
                pmsProductAttributeCategory.setPic(category.getIconUrl());
                pmsProductAttributeCategory.setName(category.getName());

                pmsProductAttributeCategoryMapper.insert(pmsProductAttributeCategory);

                List<BakCategory> categoryList = bakCategoryMapper.selectList(new QueryWrapper<BakCategory>().eq("pid", entity.getType()));
                for (BakCategory bakCategory : categoryList) {

                    PmsProductCategory pmsProductCategory1 = new PmsProductCategory();
                    pmsProductCategory1.setIcon(bakCategory.getIconUrl());
                    pmsProductCategory1.setName(bakCategory.getName());
                    pmsProductCategory1.setKeywords(bakCategory.getKeywords());
                    pmsProductCategory1.setParentId(bakCategory.getPid().longValue());
                    pmsProductCategory1.setLevel(Integer.parseInt(bakCategory.getLevel().substring(1)));
                    pmsProductCategoryMapper.insert(pmsProductCategory1);
                }
                List<Integer> ids = categoryList.stream()
                        .map(BakCategory::getId)
                        .collect(Collectors.toList());
                if (ids != null) {
                    List<BakGoods> goodsList = bakGoodsMapper.selectList(new QueryWrapper<BakGoods>().in("category_id", ids));
                    for (BakGoods gg : goodsList) {
                        createG(gg, entity.getId());
                    }
                    List<Integer> brands = goodsList.stream()
                            .map(BakGoods::getBrandId)
                            .collect(Collectors.toList());
                    if (brands != null) {
                        List<BakBrand> bakBrands = bakBrandMapper.selectBatchIds(brands);
                        if (bakBrands != null && bakBrands.size() > 0) {
                            for (BakBrand bakBrand : bakBrands) {
                                PmsBrand brand = new PmsBrand();
                                brand.setBigPic(bakBrand.getPicUrl());
                                brand.setName(bakBrand.getName());
                                brand.setShowStatus(1);
                                brand.setFactoryStatus(1);
                                brand.setLogo(bakBrand.getPicUrl());
                                brand.setSort(bakBrand.getSortOrder());
                                pmsBrandMapper.insert(brand);
                            }
                        }
                    }
                }
            });
        }*/
        return true;
    }

    @Override
    public int updateShowStatus(List<Long> ids, Integer showStatus) {
        SysStore pmsBrand = new SysStore();
        pmsBrand.setIsBoutique(showStatus);
        return storeMapper.update(pmsBrand, new QueryWrapper<SysStore>().in("id", ids));
    }

    @Override
    public int audit(List<Long> ids, Integer showStatus) {
        SysStore pmsBrand = new SysStore();
        pmsBrand.setStatus(showStatus);
        return storeMapper.update(pmsBrand, new QueryWrapper<SysStore>().in("id", ids));
    }

}
